package com.hilinos.cloud.gateway.router;

import java.util.ArrayList;
import java.util.List;

import com.hilinos.common.common.ReturnCode;
import com.hilinos.common.util.AssertUtils;
import com.hilinos.common.util.RandomUtils;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.RequestDataContext;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.http.HttpHeaders;
import org.springframework.util.ObjectUtils;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

@Slf4j
public class JsfjReactorServiceInstanceLoadBalancer implements ReactorServiceInstanceLoadBalancer {
    private final ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    private final String serviceId;

    public JsfjReactorServiceInstanceLoadBalancer(
            ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
            String serviceId) {
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
        this.serviceId = serviceId;
    }

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider.getIfAvailable();
        AssertUtils.isNotEmpty(supplier, ReturnCode.NORMAL_SYSTEM_ERROR);
        return supplier.get().next().map((list) -> getInstanceResponse(list,
                ((RequestDataContext) request.getContext()).getClientRequest().getHeaders()));
    }

    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances, HttpHeaders headers) {
        if (instances.isEmpty()) {
            if (log.isWarnEnabled()) {
                log.warn("No servers available for service: " + serviceId);
            }
            return new EmptyResponse();
        }
        // 选择一个服务实例
        String env = headers.getFirst("var_env");

        if (ObjectUtils.isEmpty(env)) {
            return new DefaultResponse(instances.get(RandomUtils.genRandomInt(instances.size())));
        }

        List<ServiceInstance> envInstances = new ArrayList<>();

        for (ServiceInstance serviceInstance : instances) {
            if (env.equals(serviceInstance.getMetadata().get("var_env"))) {
                envInstances.add(serviceInstance);
            }
        }
        if (envInstances.isEmpty()) {
            if (log.isWarnEnabled()) {
                log.warn("No servers available for service: " + serviceId);
            }
            return new EmptyResponse();
        }

        return new DefaultResponse(envInstances.get(RandomUtils.genRandomInt(envInstances.size())));
    }
}
